<template>
  <div class="app-container">
    <div v-if="compositionList">
      <div class="app-title">
        {{sampleList.name}}
      </div>
      <div>
        分类：{{sampleList.classifyName}}
      </div>
      <div class="top-app">
        编号：{{sampleList.code}}
      </div>   

      <el-button type="primary" size="small" @click="addOneTable()">新增元素</el-button>

    <div class="app-add" v-if="isAdd">
      <el-select v-model="addValue" placeholder="请选择">
        <el-option
          v-for="item in optionList"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <el-button class="p-add" type="primary" size="small" @click="addSubmit()">确认新增</el-button>
      

    </div>

    <div v-loading="loading" v-for="(item,indexFirst) in transformedData" :key="item.compositionId" class="descriptions">
      
      <el-descriptions :title=item.compositionName border >
        <template slot="extra">
          <el-button type="primary" size="small" @click="addNum(indexFirst)">新增明细</el-button>
        </template> 
                <el-descriptions-item v-for="(comp,indexSecond) in item.children" :key="comp.compositionDetlId" width="100">
                <template slot="label">
                  <span v-if="!transformedData[indexFirst].children[indexSecond].isEdit">{{transformedData[indexFirst].children[indexSecond].compositionDetlName}}</span>
                  <el-select
                    v-if="transformedData[indexFirst].children[indexSecond].isEdit"
                    :style="{ width: '100px' }"
                    v-model="transformedData[indexFirst].children[indexSecond].compositionDetlId"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="元素"
                    :remote-method="(query) => remoteMethodFront(query, item)"
                    @focus="remoteMethodFront(undefined, item)"
                    :loading="loading"
                    clearable
                    >
                    <el-option
                      v-for="item in compositiondetlList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                           
                </template>
              <div class="des">
                  <div>
                       <span v-if="!transformedData[indexFirst].children[indexSecond].isEdit">{{transformedData[indexFirst].children[indexSecond].content}}</span>
                      <el-input v-if="transformedData[indexFirst].children[indexSecond].isEdit" :style="{ width: '80px' }" v-model="transformedData[indexFirst].children[indexSecond].content"></el-input>
                              <!-- <el-input :style="{ width: '50px' }" v-model="transformedData[indexFirst].children[indexSecond].unitsAbbreviation"></el-input> -->
                      <span v-if="!transformedData[indexFirst].children[indexSecond].isEdit">{{transformedData[indexFirst].children[indexSecond].unitsAbbreviation}}</span>
                      <!-- <el-select
                        v-if="transformedData[indexFirst].children[indexSecond].isEdit"
                        :style="{ width: '90px' }"
                        v-model="transformedData[indexFirst].children[indexSecond].unitsId"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="单位"
                        :remote-method="remoteMethodBack"
                        @focus="remoteMethodBack()"
                        :loading="loading"
                        clearable
                        >
                        <el-option
                          v-for="item in unitsList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                      </el-select>  -->
                  </div>

                  <span class="right-btn">
                    <el-button @click="delNum(indexFirst,indexSecond)" type="danger" size="small" icon="el-icon-delete" plain circle></el-button>
                    <el-button v-if="!transformedData[indexFirst].children[indexSecond].isEdit" @click="editIt(indexFirst,indexSecond)" type="primary" icon="el-icon-edit" size="small" circle plain></el-button>
                    <el-button v-if="transformedData[indexFirst].children[indexSecond].isEdit" @click="editNum(indexFirst,indexSecond)" type="primary" size="small" plain>保存</el-button>
                  </span>
              </div>
                </el-descriptions-item>
      </el-descriptions>
    
    </div>  
    </div>
    <div v-else>
      <el-empty description="暂无数据"></el-empty>
    </div>
    
  </div>
</template>

<script>
import { listComposition, getComposition, delComposition, addComposition, updateComposition } from "@/api/food/detail";
import { getSample} from "@/api/food/foodmanage";
import { listCompositions, listCompositiondetl, getCompositiondetl, delCompositiondetl, addCompositiondetl, updateCompositiondetl } from "@/api/food/element";

import { listUnits } from "@/api/food/units";

// sampleId 食品样品id
// compositionDetlId  负责提供父级
// id 无具体作用，负责子级


// 成分id compositionlId
//  1：食物能量 3:脂肪酸  5:维生素 7:矿物质  

export default {
  name: "Composition",
  data() {
    return {
      optionList: [],
      isAdd: false,
      addValue: null,
      list: [],
      loading: false,
      sampleList: {},
      Did: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 《中国食物成分》食物样品描述详情表格数据
      compositionList: [],
      transformedData: [],
      compositiondetlList: [],
      unitsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 2000,
        sampleId: null,
        compositionDetlId: null,
        content: null,
        orderNum: null,
        status: null
      },
      // 表单参数
      form: {
        classifyId: 0
      },
      // 表单校验
      rules: {
        sampleId: [
          { required: true, message: "食物样品描述id不能为空", trigger: "blur" }
        ],
        compositionDetlId: [
          { required: true, message: "食物成分表明细id不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
 
  methods: {
    addOneTable(){
      this.isAdd = true;
    },
    addSubmit(){
      const foundObject = this.optionList.find(obj => obj.id === this.addValue);
      console.log(foundObject);
      this.transformedData.unshift({
        compositionName: foundObject.name,
        compositionDetlId: this.addValue,
        children: [
          {
            compositionDetlId: '',
            compositionDetlName: '',
            content: '',
            unitsAbbreviation: '',
            unitsId: '',
            sampleId: this.$route.query.id,
            isEdit: true
           }          
        ]
      })

      this.isAdd = false;
      this.addValue = ''

    },
    addNum(indexFirst, indexSecond){
      this.transformedData[indexFirst].children.push({
        compositionDetlId: '',
        compositionDetlName: '',
        content: '',
        unitsAbbreviation: '',
        unitsId: '',
        sampleId: this.transformedData[indexFirst].children[0].sampleId,
        isEdit: true
      })
    },
    transFormData(compositionList){
      let transformedData = []
      // 遍历原始数据
      compositionList.forEach(item => {
        // 查找已存在的compositionId
        const existingComposition = transformedData.find(d => d.compositionId === item.compositionId);
        if (existingComposition) {
          // 如果已存在，将compositionDetlId和compositionDetlName添加到children数组中
          existingComposition.children.push({
            id: item.id,
            sampleId: item.sampleId,
            compositionDetlId: item.compositionDetlId,
            compositionDetlName: item.compositionDetlName,
            unitsAbbreviation: item.unitsAbbreviation,
            unitsId: item.unitsId,
            content: item.content,
            isEdit: false
          });
        } else {
          // 如果不存在，创建新的composition对象，并添加到transformedData数组中
          transformedData.push({
            compositionId: item.compositionId,
            compositionName: item.compositionName,
            children: [
              {
                id: item.id,
                sampleId: item.sampleId,
                compositionDetlId: item.compositionDetlId,
                compositionDetlName: item.compositionDetlName,
                unitsAbbreviation: item.unitsAbbreviation,
                unitsId: item.unitsId,
                content: item.content,
                isEdit: false
              }
            ]
          });
        }
      });
      return transformedData;

    },

    /** 查询《中国食物成分》食物样品描述详情列表 */
    getList() {
      this.queryParams.sampleId = this.$route.query.id;
      this.loading = true;
      listComposition(this.queryParams).then(response => {
        this.compositionList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.transformedData = this.transFormData(this.compositionList);
      });
      listCompositions({
        pageNum: 1,
        pageSize: 2000,
      }).then(response => {
        this.optionList = response.rows;
      });

      getSample(this.queryParams.sampleId ).then(response => {
        this.sampleList = response.data;
      });
      listCompositiondetl(this.queryParams).then(response => {
        this.compositiondetlList = response.rows;
      });
      listUnits(this.queryParams).then(response => {
        this.unitsList = response.rows;
      });      
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sampleId: null,
        compositionDetlId: null,
        content: null,
        remark: null,
        orderNum: null,
        updateTime: null,
        updateBy: null,
        createTime: null,
        createBy: null,
        delFlag: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加《中国食物成分》食物样品描述详情";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getComposition(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改《中国食物成分》食物样品描述详情";
      });
    },
    /** 提交按钮 */
    editNum(indexFirst,indexSecond) {
          // if (this.form.id != null) {
          //   updateComposition(this.form).then(response => {
          //     this.$modal.msgSuccess("修改成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // } 
          console.log('static',this.transformedData[indexFirst].children[indexSecond]);
          let trData = this.transformedData[indexFirst].children[indexSecond]
            if(trData.id){
              updateComposition({
                "id": trData.id,
                "sampleId": trData.sampleId,
                "compositionDetlId": trData.compositionDetlId,
                "compositionId": trData.compositionId,
                "unitsId": trData.unitsId,
                "content": trData.content,
                "status": "0"
              }).then(response => {
                this.$modal.msgSuccess("保存成功");
                this.open = false;
                this.getList();
              }); 
            } else {
              addComposition({
                "sampleId": trData.sampleId,
                "compositionDetlId": trData.compositionDetlId,
                "compositionId": trData.compositionId,
                "unitsId": trData.unitsId,
                "content": trData.content,
                "status": "0"                
              }).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
            this.transformedData[indexFirst].children[indexSecond].isEdit = false

    },
    editIt(indexFirst,indexSecond){
      this.transformedData[indexFirst].children[indexSecond].isEdit = true
    },
    /** 删除按钮操作 */
    delNum(indexFirst,indexSecond) {
      const ids = this.transformedData[indexFirst].children[indexSecond].id;
      if(ids){
        this.$modal.confirm('是否确认删除《中国食物成分》食物样品描述详情编号为"' + ids + '"的数据项？').then(function() {
          return delComposition(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      } else {
        this.transformedData[indexFirst].children = this.transformedData[indexFirst].children.slice(0, -1);
        if(this.transformedData[indexFirst].children.length === 0){
          this.transformedData.splice(indexFirst, 1);
          console.log('static',this.transformedData);
        }
      }

    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('food/composition/export', {
        ...this.queryParams
      }, `composition_${new Date().getTime()}.xlsx`)
    },

    remoteMethodFront(query, item) {
        if (query !== '') {
          listCompositiondetl({
            name: query,
            pageNum: 1,
            pageSize: 2000,
            compositionId: item.compositionId || item.compositionDetlId
          }).then(response => {
              this.compositiondetlList = response.rows;
            });

        } else {
          this.compositiondetlList = [];
        }
      },

    remoteMethodBack(query) {
        if (query !== '') {
          listUnits({
            name: query,
            pageNum: 1,
            pageSize: 2000
          }).then(response => {
              this.unitsList = response.rows;
            });

        } else {
          this.unitsList = [];
        }
      }      


  }
};
</script>


<style lang="scss" scoped>

.descriptions{
  margin-top: 50px;
}
.app-title{
  font-size: 30px;
  font-weight: 800;
  margin-top: 40px;
}
.app-add{
  margin-top: 50px;
}
.top-app{
  margin-bottom: 30px;
}

.p-add{
  margin-left: 20px;
}

.value{
  font-size: 25px;
  font-weight: 800;
  position: relative;
  top: 20px;
}
.del-btn{
  margin-left: 10px;
}
.des{
  display: flex;
  justify-content: space-around;
  align-items: center;
}
</style>